package com.petrochina.cloudconfig.util;

import com.jcraft.jsch.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * 远程ssh工具
 */
public class SSH2Util {
    /**
     * copy file to server
     * @param host
     * @param username
     * @param password
     * @param localFilePath
     * @param remoteFilePath
     */
    public static void copyFileToServer(String host,String username,String password,String localFilePath,String remoteFilePath){
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(username, host, 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            //connect
            session.connect(3*1000);

            //get channel
            ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
            //
            channel.put(new FileInputStream(localFilePath), remoteFilePath,new MyProgressMonitor(), ChannelSftp.OVERWRITE);

            channel.disconnect();
            //关闭会话
            session.disconnect();


        } catch (JSchException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
}
